import type { RouteRecordRaw } from "vue-router";
import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import {ElMessage} from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import userinfoApi, { type userinfoModel } from '@/api/userinfo';
import router from "@/router";
import { cloneDeep } from 'lodash'


const filterRoutesHandler = (routes: RouteRecordRaw[], routesName: string[]) => {

  let result = routes.filter(route => {

    if (route.children) { 
      route.children = filterRoutesHandler(route.children, routesName);
    }

    return routesName.includes(route.name as string);
  })

  return result;
}


const addRoutes = (allRoutes: RouteRecordRaw[]) => {
  allRoutes.forEach(route => {
    router.addRoute(route);
  })
}



interface UserInfoState {
  token: string,
  userinfo: userinfoModel,
  menuRoutes: RouteRecordRaw[]
}

const initUserinfo = (): userinfoModel => ({
  avatar: '',
  name: '',
  buttons: [],
  roles: [],
  routes: []
}) 

export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,

    userinfo: initUserinfo(), 

    menuRoutes: []
  }),

  actions: {

    async login (username: string, password: string) {
      try {
        let result = await userinfoApi.login({ username, password });
        this.token = result.token; 
        setToken(result.token) 
      } catch (error) {
        ElMessage.error('登录失败,请重试'); 
        return Promise.reject(error); 
      }
    },

    async getInfo () {
      try {
        let result = await userinfoApi.info(); 
        

        this.userinfo = result; 

        const filterRoutes = filterRoutesHandler( cloneDeep(allAsyncRoutes), result.routes); 
        const allRoutes = staticRoutes.concat(filterRoutes, anyRoute); 
        this.menuRoutes = allRoutes;
        
        addRoutes(allRoutes); 



        
      } catch (error) {
        ElMessage.error('获取个人用户信息失败,请重试')
        return Promise.reject(error); 
      }
    },

    async logout () {
      try {
        await userinfoApi.logout();

        this.reset();

      } catch (error) {
        ElMessage.error('退出登录失败,请重试')
        return Promise.reject(error);
      }
    },

    reset () {
      removeToken()
      this.token = ''
      this.userinfo = initUserinfo();
    },



  },
});
